var Shell=require("electron");
init();
function init(){
	Shell.app.on("ready",onReady);
	Shell.ipcMain.on("focus",focus);
	Shell.ipcMain.on("setTitle",setTitle);
}
function start(){
	var mainCode=Shell.fs.readFileSync(Shell.path+"code/Main.js")+"";
	mainCode=mainCode.replace(/\r/g,"");
	var isDesign=mainCode.indexOf("//[design]=>")>-1;
	var n=mainCode.indexOf("//[title]=>");
	var screenSize=Shell.screen.getPrimaryDisplay().workAreaSize;
	Shell.win=new Shell.BrowserWindow({
		width:500,
		height:screenSize.height,
		show:false,
		frame:true,
		title:"",
		alwaysOnTop:false,
		resizable:false,
		autoHideMenuBar:true
	});
	var size=Shell.win.getContentSize();
	size[0]=Math.ceil(size[1]*610/960);
	Shell.win.setContentSize(size[0],size[1]);
	size=Shell.win.getSize();
	Shell.win.setPosition(screenSize.width-size[0],0);
	Shell.win.show();
	Shell.win.loadURL("file://"+Shell.path+"index.html");
}
function initServer(){
    Shell.server=Shell.http.createServer(function(request,response){
    	var url=request.url.slice(1).replace(/\?.+$/g,"");
    	if(!url) url="index.html";
    	url=Shell.path+url;
    	var ext=url.replace(/[^\.]+\./g,"").toLowerCase();
    	if(!Shell.fs.existsSync(url)){
    		response.writeHead(500,{"Content-Type": "text/plain"});
    		response.write("File is not exists.");
    		response.end();
    	}
    	else if(ext=="txt"||ext=="js"||ext=="htm"||ext=="html"){
    		response.writeHead(200,{"Content-Type":"text/html;charset=UTF-8"});
    		var code=Shell.fs.readFileSync(url);
	        response.end(code);
    	}
    	else{
    		var type="application/ocelet-stream";
    		if(ext=="png") type="image/png";
    		if(ext=="jpg") type="image/jpeg";
    		if(ext=="mp3") type="audio/mp3";
    		if(ext=="wav") type="audio/wav";
		    response.writeHead(200,{"Content-Type":type});
		    var file=Shell.fs.readFileSync(url, "binary");
		    response.write(file, "binary");
		    response.end();
    	}
 	});
 	Shell.server.on("error",onServerError);
	Shell.server.listen(8000);
}
function onServerError(evt) {
	var str=evt+"";
	if(str.indexOf("Error: listen")==0){
		setTimeout(initServer,500);
	}
}
function onReady(){
	Shell.fs=require("fs");
	Shell.os=require("os");
	Shell.http=require("http");

	Shell.path=Shell.app.getAppPath().replace(/\\/g,"/")+"/";
	initServer();
	start();
	if(!Shell.win) Shell.app.quit();
}
function focus(){
	Shell.win.focus();
}
function setTitle(evt,title){
	Shell.win.setTitle(title+"");
}
function alert(text){
	Shell.dialog.showErrorBox("",text+"");
}
